<template>
  <div class="min-h-screen flex flex-col bg-gray-100">
    <!-- Header -->
    <header class="w-full h-16 bg-blue-600 text-white flex justify-center items-center shadow-md fixed top-0 left-0 z-50">
      <p class="text-xl font-semibold">在线支付</p>
    </header>

    <main class="flex-1 pt-16 px-4 pb-24 space-y-4">
      <h3 class="text-sm text-gray-500 font-light mt-2">订单信息：</h3>

      <div
          class="bg-white p-4 rounded-lg shadow-sm flex justify-between items-center text-base text-gray-700 cursor-pointer transition duration-200 hover:bg-gray-50"
          @click="toggleDetail"
      >
        <p class="font-medium">
          {{ shopName }}
          <i
              class="fa fa-caret-down ml-1 transition-transform duration-300"
              :class="{ 'rotate-180': isDetailVisible }"
          ></i>
        </p>
        <p class="text-orange-500 font-bold">￥{{ totalPrice.toFixed(2) }}</p>
      </div>

      <transition name="slide">
        <ul v-show="isDetailVisible" class="bg-white rounded-lg shadow-sm overflow-hidden">
          <li
              v-for="(item, index) in orderItems"
              :key="index"
              class="flex justify-between items-center px-4 py-2 border-b last:border-0 border-gray-200"
          >
            <p class="text-sm text-gray-600">{{ item.name }} x {{ item.quantity }}</p>
            <p class="text-sm text-gray-600">￥{{ item.price.toFixed(2) }}</p>
          </li>
          <li class="flex justify-between items-center px-4 py-2">
            <p class="text-sm text-gray-600">配送费</p>
            <p class="text-sm text-gray-600">￥{{ deliveryFee.toFixed(2) }}</p>
          </li>
        </ul>
      </transition>

      <div class="space-y-3">
        <label
            class="flex items-center p-4 bg-white border border-gray-200 rounded-xl shadow-sm cursor-pointer transition-all duration-200 hover:shadow-md active:bg-gray-100"
        >
          <input
              type="radio"
              name="paymentMethod"
              value="alipay"
              v-model="selectedPayment"
              class="form-radio h-5 w-5 text-blue-600 mr-3"
          >
          <img src="/img/alipay.png" alt="支付宝" class="w-16 h-auto object-contain mr-3">
          <span class="text-base text-gray-700 font-medium">支付宝</span>
        </label>

        <label
            class="flex items-center p-4 bg-white border border-gray-200 rounded-xl shadow-sm cursor-pointer transition-all duration-200 hover:shadow-md active:bg-gray-100"
        >
          <input
              type="radio"
              name="paymentMethod"
              value="wechat"
              v-model="selectedPayment"
              class="form-radio h-5 w-5 text-green-600 mr-3"
          >
          <img src="/img/wechat.png" alt="微信" class="w-16 h-auto object-contain mr-3">
          <span class="text-base text-gray-700 font-medium">微信支付</span>
        </label>
      </div>

      <div class="mt-6">
        <button
            @click="handleConfirm"
            class="w-full h-12 bg-green-500 text-white text-base font-bold rounded-lg shadow-md hover:bg-green-600 transition-colors duration-200 active:opacity-90"
        >
          确认支付
        </button>
      </div>
    </main>

    <FooterMenu />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import FooterMenu from "@/components/common/FooterMenu.vue";
import { useOrderStore } from '@/stores/user'; // Import the order store

const route = useRoute()
const router = useRouter()
const orderStore = useOrderStore(); // Initialize the order store

// Control order detail display
const isDetailVisible = ref(false)

// Toggle order detail
const toggleDetail = () => {
  isDetailVisible.value = !isDetailVisible.value
}

// Payment method selection
const selectedPayment = ref<'alipay' | 'wechat'>('alipay') // Default to Alipay

// Reactive variables for order data
const shopName = ref('万家饺子（软件园E18店）')
const deliveryFee = ref(3)
const orderItems = ref([])
const totalPrice = computed(() => {
  if (orderItems.value.length === 0) {
    return 0;
  }
  const itemsTotal = orderItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
  return itemsTotal + deliveryFee.value
})

onMounted(() => {
  // Retrieve data from route query
  const shopNameQuery = route.query.shopName as string || '万家饺子（软件园E18店）';
  const deliveryFeeQuery = parseFloat(route.query.deliveryFee as string) || 3;
  const itemsQuery = decodeURIComponent(route.query.items as string || '[]');

  shopName.value = shopNameQuery;
  deliveryFee.value = deliveryFeeQuery;

  try {
    const parsed = JSON.parse(itemsQuery)
    if (Array.isArray(parsed)) {
      orderItems.value = parsed
    }
  } catch (e) {
    console.error('解析订单数据失败', e)
    console.log('订单数据异常')
  }
})

// Payment button logic
const handleConfirm = () => {
  if (!selectedPayment.value) {
    alert('请选择支付方式')
    return
  }

  // Create a new order object
  const newOrder = {
    id: Date.now().toString(), // Simple unique ID
    shopName: shopName.value,
    items: orderItems.value,
    deliveryFee: deliveryFee.value,
    totalPrice: totalPrice.value,
    status: '已支付', // Set status as paid upon confirmation
    paymentMethod: selectedPayment.value // Save the selected payment method
  };

  // Add the order to the store
  orderStore.addOrder(newOrder);

  alert(`使用 ${selectedPayment.value === 'alipay' ? '支付宝' : '微信'} 支付成功！`);
  router.push('/order-list'); // Navigate to order list page
}
</script>


